<?php

namespace control;

/*
*销售发货单类
*/

class saleSendOrderPrintClass extends \control\adIndexClass
{
    private const page = 'saleSendOrderPrint';
    private const table = 'sale_send_order';
    private const tableMx = 'sale_send_order_detail';
    private const title = '打印销售发货单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'     => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'companyName' => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'tag'         => [
                        'name'  => "单据标签",
                        'width' => 300,
                    ],
                    'manager'     => [
                        'name'  => '销售员',
                        'width' => 200,
                    ],
                    'recordDate'  => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'state'       => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "标签"   => text(array("name" => "tages")),
                    '客户名称' => \control\clientProfileClass::kehuSelect(array('title' => '')),
                ],
                [
                    '销售员'  => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
//                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//证件编号
        );
        //全等查询数组
        $equal = array(
            "stid"  => $this->post('stid'),
            "khid"  => $this->post('khid'),
            'coid'  => self::$coid,
            'state' => '已确认'
        );
        $and = self::timeComparison(date("Y-m-d").'~'.date('Y-m-d'), 'date', 'recordDate');
        if ($this->post('tages')) {
            $and     .= " and (";
            $tagsArr = explode('，', $this->post('tages'));
            foreach ($tagsArr as $index => $tag) {
                $and .= $index == 0 ? "tags like '%" . $tag . "%'" : " and tags like '%" . $tag . "%'";
            }
            $and .= ")";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
//                "edit"   => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
//                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
//                'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
//                'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=销售发货单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "companyName":
                        $kehu  = query('kehu', "khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "tag":
                        $tag   = \control\orderTagClass::getTagName($array['id']);
                        $row[] = $tag;
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money'], 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button   = "";
        $numTotal = find(array(
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money"
        ));
        $total    = [
            'money' => self::lostZero($numTotal['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array  = explode(',', $listId);
            $data   = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {

        $id                  = $param ?: $this->get('id');
        $info                = query(self::table, " id = '$id'");
        $sale_order                = query('sale_order', " id = '$info[orderId]'");
        $department_name                = query('department', " id = '$info[departmentId]'");
        $logistics_car                = query('logistics_car', " id = '$sale_order[car_id]'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title']       = '销售发货单';
        $info['printTime']   = $this->time;
        $info['stid']        = self::findStaff($info['stid']);
        $info['checkId']     = '';
        $info['khName']      = query('kehu', "khid = '$info[khid]'")['companyName'];
        $info['contractId']  = query('sales_contract', "id = '$info[contractId]'")['name'];
        $info['qr']          = "source=" . self::table . "&id=" . $info['id'];
        $info['tags']        = orderTagClass::getTagName($info['id']);
        $info['car_id']        = $logistics_car['shortName'].$logistics_car['carNo'];
        $info['delivery_name']        = self::findStaff($sale_order['delivery_name']);
        $info['delivery_manage']        = self::findStaff($sale_order['delivery_manage']);
        $info['department_name']        = $department_name['name'];
        $detail              = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items               = [];
        $x                   = 1;
        $totalNum            = 0;
        $totalMoney          = 0;
        foreach ($detail as $array) {
            $material    = query('material', "id = '$array[materialId]'");
            $saleOrderMx = query("sale_order_detail", "id = '$array[saleOrderMxId]'");
            $saleOrder   = query('sale_order', "id = '$saleOrderMx[orderId]'");
            $items[]     = [
                'no'               => $x,
                'materialCode'     => $material['code'],
                'typeName'     => $material['typeName'],
                'materialName'     => $material['name'],
                'warehouse'        => warehouseClass::getName($array['warehouseId']),
                'price'            => self::lostZero($array['price'], 'pricePrecision'),
                'rate'             => ($array['rate'] * 100) . '%',
                'taxMoney'         => self::lostZero($array['taxMoney'], 'amount'),
                'khMaterialName'   => $array['khMaterialName'],
                'khMaterialCode'   => $array['khMaterialCode'],
                'moneyWithOutTax'  => self::lostZero($array['money'] - $array['taxMoney'], 'amount'),
                'money'            => self::lostZero($array['money'], 'amount'),
                'model'            => $material['model'],
                'unit'             => $array['unit'],
                'num'              => self::lostZero($array['num'], 'numPrecision'),
                'packing_quantity' => $array['packing_quantity'],
                'box_capacity'     => $array['box_capacity'],
                'remainder'        => $array['remainder'],
                'sourceNo'         => $saleOrder['orderNo'],
                'text'         => $array['text'],

            ];
            $x++;
            $totalNum   += $array['num'];
            $totalMoney += $array['money'];
        }
        $append         = [
            'no'    => '合计',
            'num'   => self::lostZero($totalNum, 'amount'),
            'money' => self::lostZero($totalMoney, 'amount'),
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info, '销售发货单');
        } else {
            return $info;
        }
    }
}
